/*
 * @Author: liusheng
 * @Date: 2022-04-17 21:42:37
 * @LastEditors: liusheng
 * @LastEditTime: 2022-06-19 11:56:05
 * @Description: 剑指 Offer II 031. 最近最少使用缓存
 * email:liusheng613@126.com
 * Copyright (c) 2022 by liusheng/liusheng, All Rights Reserved. 
 * 
 剑指 Offer II 031. 最近最少使用缓存
运用所掌握的数据结构，设计和实现一个  LRU (Least Recently Used，最近最少使用) 缓存机制 。

实现 LRUCache 类：

LRUCache(int capacity) 以正整数作为容量 capacity 初始化 LRU 缓存
int get(int key) 如果关键字 key 存在于缓存中，则返回关键字的值，否则返回 -1 。
void put(int key, int value) 如果关键字已经存在，则变更其数据值；如果关键字不存在，则插入该组「关键字-值」。当缓存容量达到上限时，它应该在写入新数据之前删除最久未使用的数据值，从而为新的数据值留出空间。
 

示例：

输入
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
输出
[null, null, null, 1, null, -1, null, -1, 3, 4]

解释
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // 缓存是 {1=1}
lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}
lRUCache.get(1);    // 返回 1
lRUCache.put(3, 3); // 该操作会使得关键字 2 作废，缓存是 {1=1, 3=3}
lRUCache.get(2);    // 返回 -1 (未找到)
lRUCache.put(4, 4); // 该操作会使得关键字 1 作废，缓存是 {4=4, 3=3}
lRUCache.get(1);    // 返回 -1 (未找到)
lRUCache.get(3);    // 返回 3
lRUCache.get(4);    // 返回 4
 

提示：

1 <= capacity <= 3000
0 <= key <= 10000
0 <= value <= 105
最多调用 2 * 105 次 get 和 put
 

进阶：是否可以在 O(1) 时间复杂度内完成这两种操作？
 */

/*
小贴士

在双向链表的实现中，使用一个伪头部（dummy head）和伪尾部（dummy tail）标记界限，
这样在添加节点和删除节点的时候就不需要检查相邻的节点是否存在。
*/
#include <unordered_map>
#include <list>
using namespace std;

struct DLinkNode
{
    int key;
    int val;
    DLinkNode * pre;
    DLinkNode * next;
    DLinkNode():key(0),val(0),pre(nullptr),next(nullptr) { }
    DLinkNode(int key,int val,DLinkNode * pre,DLinkNode * next):key(key),val(val),pre(pre),next(next) { }
    DLinkNode(int key,int val):key(key),val(val),pre(nullptr),next(nullptr) {}
};

class LRUCache {
public:
    LRUCache(int capacity):capacity(capacity) {
        dummyHead = new DLinkNode();
        dummyTail = new DLinkNode();
        
        dummyHead->next = dummyTail;
        dummyTail->pre = dummyHead;
    }
    ~LRUCache()
    {
        if (dummyHead)
        {
            delete dummyHead;
        }
        
        if(dummyTail)
        {
            delete dummyTail;
        }
    }
    
    int get(int key) {
        if (location.count(key))
        {
            DLinkNode * node = location[key];
            
            //delete node from list
            node->pre->next = node->next;
            node->next->pre = node->pre;
            
            //insert node to the list head
            node->pre = dummyHead;
            node->next = dummyHead->next;
            
            dummyHead->next->pre = node;
            dummyHead->next = node;
            
            return location[key]->val;
        }
        
        return -1;
    }
    
    void put(int key, int value) {
        if (location.count(key))
        {
            DLinkNode * node = location[key];
            node->val = value;
            
            //delete node from list
            node->pre->next = node->next;
            node->next->pre = node->pre;
            
            //insert node to the list head
            node->pre = dummyHead;
            node->next = dummyHead->next;
            
            dummyHead->next->pre = node;
            dummyHead->next = node;
        }
        else
        {
            if (location.size() >= capacity)
            {
                DLinkNode * tailNode = dummyTail->pre;
                //delete the tail node
                tailNode->pre->next = dummyTail;
                dummyTail->pre = tailNode->pre;
                
                //erase from location
                location.erase(tailNode->key);
                //delete the node
                delete tailNode;
            }
            
            //node->pre link to dummyHead,node->next link to dummyHead->next(origin head)
            DLinkNode * node = new DLinkNode(key,value,dummyHead,dummyHead->next);
            location[key] = node;
            //origin head ->pre link to node
            dummyHead->next->pre = node;
            //dummyHead->next point to node,node become the new head
            dummyHead->next = node;
        }
    }
private:
    unordered_map<int,DLinkNode *> location;
    int capacity;
    DLinkNode * dummyHead;
    DLinkNode * dummyTail;
};

//same as above,but use std::list instead user-defined struct DLinkNode
class LRUCache {
public:
    LRUCache(int capacity):capacity(capacity) {

    }
    
    int get(int key) {
        if (keyLocation.count(key))
        {
            auto iter = keyLocation[key];
            /*
            Transfers elements from one list to another.
            No elements are copied or moved, only the           
            internal pointers of the list nodes are re-pointed.
            */ 
            lruList.splice(lruList.begin(),lruList,iter);
            return iter->second;
        }

        return -1;
    }
    
    void put(int key, int value) {
        if (keyLocation.count(key))
        {
            keyLocation[key]->second = value;
            lruList.splice(lruList.begin(),lruList,keyLocation[key]);
        }
        else
        {
            if (keyLocation.size() >= capacity)
            {
                keyLocation.erase(lruList.back().first);
                lruList.pop_back();
            }

            lruList.emplace_front(make_pair(key,value));
            keyLocation[key] = lruList.begin();
        }
    }

private:
    const int capacity;
    list<pair<int,int>> lruList; //key,value list,key is used for remove the tail form the location
    unordered_map<int,list<pair<int,int>>::iterator> keyLocation;
};
